package ar.edu.itba.infovis.TPF.json;

import java.io.IOException;

import java.util.Locale;

import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;

public class CustomJSONTwitterDateDeserializer extends JsonDeserializer<DateTime> {

	@Override
	public DateTime deserialize(JsonParser jp, DeserializationContext ctxt)
			throws IOException, JsonProcessingException {
		
		String dateStr = jp.getText();
		
		DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
		.appendDayOfWeekShortText()
		.appendLiteral(" ")
		.appendMonthOfYearShortText()
		.appendLiteral(" ")
		.appendDayOfMonth(2)
		.appendLiteral(" ")
		.appendHourOfDay(2)
		.appendLiteral(":")
		.appendMinuteOfHour(2)
		.appendLiteral(":")
		.appendSecondOfMinute(2)
		.appendLiteral(" ")
		.appendTimeZoneOffset("+0000", false, 2, 4)
		.appendLiteral(" ")
		.appendYear(4, 4)
		.toFormatter()
		.withLocale(Locale.US);
		
		DateTimeFormatter dateTimeFormatter2 = new DateTimeFormatterBuilder()
		.appendDayOfWeekShortText()
		.appendLiteral(",")
		.appendLiteral(" ")
		.appendDayOfMonth(2)
		.appendLiteral(" ")
		.appendMonthOfYearShortText()
		.appendLiteral(" ")
		.appendYear(4, 4)
		.appendLiteral(" ")
		.appendHourOfDay(2)
		.appendLiteral(":")
		.appendMinuteOfHour(2)
		.appendLiteral(":")
		.appendSecondOfMinute(2)
		.appendLiteral(" ")
		.appendTimeZoneOffset("+0000", false, 2, 4)
		.toFormatter()
		.withLocale(Locale.US);
		
		DateTime result = null;
		try{
		result = dateTimeFormatter.parseDateTime(dateStr);
		} catch (IllegalArgumentException e) {
			result = dateTimeFormatter2.parseDateTime(dateStr);
		}
		return result;
	}

}
